package com.loongxun.playwithyou.wxapi;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.android.phone.mrpc.core.Request;
import com.loongxun.playwithyou.ApiInterface;
import com.loongxun.playwithyou.bean.SendRequest;
import com.loongxun.playwithyou.network.MyHttpClientRespenseHandler;
import com.loongxun.playwithyou.network.nHttpClient;
import com.loongxun.playwithyou.util.ToastView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

/**
 * Created by Administrator on 2017/8/9.
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    private static String TAG = "WXEntryActivity";
    private IWXAPI api;
    private SharedPreferences shared;
    private SharedPreferences.Editor editor;
    private Context context;
    private SendRequest send;

    public static AsyncHttpClient client;

    private static String GET_REQUEST_ACCESS_TOKEN =
            "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

    private static String GET_REQUEST_USER_INFO =
            "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        shared = getSharedPreferences("userInfo", 0);
        editor = shared.edit();
        context = WXEntryActivity.this;
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, ApiInterface.APP_ID, false);
        api.handleIntent(getIntent(), this);
    }

    @Override
    public void onReq(BaseReq baseReq) {
        Log.i(TAG, "onReq<------------------------------");
    }

    @Override
    public void onResp(BaseResp resp) {
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                String code = ((SendAuth.Resp) resp).code;
                Log.i(TAG, "微信登陆获取code="+code);
                //获取微信登陆Token凭证
                String requestToken = getTokenRequest(code);
//                Log.i(TAG, "微信登陆获取token网址="+requestToken);
                getToken(requestToken, getTokenHandler);
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                Toast.makeText(this, "取消!", Toast.LENGTH_LONG).show();
                editor.putString("pay_result", "fail");
                editor.commit();//提交修改
                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                Toast.makeText(this, "被拒绝", Toast.LENGTH_LONG).show();
                editor.putString("pay_result","fail");
                editor.commit();//提交修改
                finish();
                break;
            default:
                Toast.makeText(this, "失败!", Toast.LENGTH_LONG).show();
                editor.putString("pay_result", "fail");
                editor.commit();//提交修改
                finish();
                break;
        }
    }

    /**
     * 获取根据CODE得到的微信授权Token的Get请求地址
     * @param code
     * @return
     */
    private static String getTokenRequest(String code){
        String tokenRequest = GET_REQUEST_ACCESS_TOKEN.replace("APPID", ApiInterface.APP_ID).
                replace("SECRET", ApiInterface.AppSerect).
                replace("CODE",code);
        return tokenRequest;
    }

    /**
     * 获取微信用户信息的Get请求地址
     * @param openid
     * @param access_token
     * @return
     */
    private static String getUserInfot(String openid,String access_token){
        String tokenRequest = GET_REQUEST_USER_INFO.replace("ACCESS_TOKEN", access_token).
                replace("OPENID",openid);
        return tokenRequest;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
        finish();
    }

    public void getToken(String url, AsyncHttpResponseHandler handler) {
        client = new AsyncHttpClient();
        client.post(url, handler);
    }

    private AsyncHttpResponseHandler getTokenHandler = new JsonHttpResponseHandler() {

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            try {
                String openid = response.getString("openid");
                String access_token = response.getString("access_token");
                if (!"".equals(openid) && !"".equals(access_token)) {
                    getToken(getUserInfot(openid,access_token),getUserHandler);
                }
            } catch (JSONException e) {
                Log.i(TAG, "微信登陆获取Token失败原因"+response.toString());
                ToastView toast = new ToastView(context, "授权失败");
                toast.show();
                finish();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Log.i(TAG, "微信登陆获取Token失败原因"+responseString);
            ToastView toast = new ToastView(context, "授权失败");
            toast.show();
            finish();
        }
    };

    private AsyncHttpResponseHandler getUserHandler = new JsonHttpResponseHandler() {

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            try {
//                String openid = response.getString("openid");
                String unionid = response.getString("unionid");
                String nickname = response.getString("nickname");
                String headimgurl = response.getString("headimgurl");
                if (!"".equals(unionid)) {
                    send = new SendRequest();
//                    send.openid = openid;
                    send.unionid = unionid;
                    send.nickname = nickname;
                    send.headimgurl = headimgurl;
                    //注册
                    nHttpClient.getAll(ApiInterface.WX_LOGIN, send.toWxLoginJson().toString(), signinHandler);
                }else {
                    Log.i(TAG, "获取用户信息失败原因"+response.toString());
                    ToastView toast = new ToastView(context, "获取用户信息失败");
                    toast.show();
                    finish();
                }
            } catch (JSONException e) {
                Log.i(TAG, "获取用户信息失败原因"+response.toString());
                ToastView toast = new ToastView(context, "获取用户信息失败");
                toast.show();
                finish();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Log.i(TAG, "获取用户信息失败原因"+responseString);
            ToastView toast = new ToastView(context, "获取用户信息失败");
            toast.show();
            finish();
        }
    };

    private MyHttpClientRespenseHandler signinHandler = new MyHttpClientRespenseHandler() {

        @Override
        public void success(JSONObject json) {
            Integer succeed = json.optJSONObject("status").optInt("succeed", 0);
            if (succeed == 1) {
                try {
                    JSONObject jsonObject = json.getJSONObject("data").getJSONObject("user");
                    editor.putString("user_id", jsonObject.getString("user_id"));
                    String user_photo = jsonObject.getString("user_photo");
                    if (user_photo.equals("null")) {
                        user_photo = "";
                    }
                    String user_name = jsonObject.getString("user_name");
                    if (user_name.equals("null")) {
                        user_name = "";
                    }
                    String user_phone = jsonObject.getString("user_phone");
                    if (user_phone.equals("null")) {
                        user_phone = "";
                    }
                    String password = jsonObject.getString("user_password");
                    if (password.equals("null")) {
                        password = "";
                    }
                    editor.putString("user_phone", user_phone);
                    editor.putString("user_photo", user_photo);
                    editor.putString("user_name", user_name);
                    editor.putString("password", password);
                    editor.putString("pay_result", "success");
                    editor.commit();//提交修改
                    finish();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else {
                String error_desc = json.optJSONObject("status").optString("error_desc");
                new ToastView(context, error_desc).show();
                finish();
            }
        }

        @Override
        public void faile(String json) {
            new ToastView(context, json).show();
            finish();
        }
    };
}
